package com.itboy.message.config;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itboy.message.properties.WeChatMessageProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@EnableConfigurationProperties(value= WeChatMessageProperties.class)
@Configuration
@Slf4j
public class WxAutoConfiguration {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeChatMessageProperties weChatMessageProperties;

    private String wxAccessToken;

    public String getWxAccessToken() {
        return wxAccessToken;
    }

    public void setWxAccessToken(String wxAccessToken) {
        this.wxAccessToken = wxAccessToken;
    }

    /**
     * 这个spring实现了这个注解的规范
     * 所有bean对象创建完以后执行，在项目启动完成之前执行
     * 限制 不能有返回值也不能有参数
     */
    @PostConstruct
    public void tokenInit() {
        getAccessToken();
    }
    /**
     * 获取微信access_token 两小时失效 再试获取
     */
    @Scheduled(initialDelay = 7100 * 1000, fixedRate = 7100 * 1000)
    public void getAccessToken(){
        String accessTokenUrl = weChatMessageProperties.getAccessTokenUrl();
        //发请求
        String realUrl = String.format(accessTokenUrl, weChatMessageProperties.getAppId(), weChatMessageProperties.getAppSecret());
        String accessTokenJsonStr = restTemplate.getForObject(realUrl, String.class);

        JSONObject jsonObject = JSONUtil.parseObj(accessTokenJsonStr);
        String accessToken = jsonObject.get("access_token").toString();
        if (StrUtil.isNotBlank(accessToken)) {
            // 保存起来 可以放在redis里面
            wxAccessToken = accessToken;
        } else {
            log.error("获取微信的access_token失败了");
        }
    }
}
